import { Loading } from 'element-ui';
import { DATA } from './data';
import { NAV, PARAMS } from './navigation';
import { TF } from './tf';
import { ICON } from './icon';
import { PAINT } from './paint'
import store from '../store';
import { showStationDetail } from './methods'
let UI = UI || {
	/**
	 * 点击站点图标显示站点详情
	 * **/
	wpClickHandle: (event) => {
		var waypointName = event.currentTarget.name;
		showStationDetail(waypointName)
	},

	/**
	 * 轮廓，激光，地图等显示/隐藏
	 * key:value形式
	 * **/
	display: (val) => {
		//如果存在key
		if (val.hasOwnProperty('property')){
			var topicName = val.property + 'Topic';
			var stageName = val.property + 'Stage';
			var topic = DATA.topic[topicName];
			var stageObj = DATA[stageName];
			//如果value=true显示，就订阅话题
			if (val.value){
				var msgName = val.property + 'Msg';
				if (msgName === 'mapMsg'){
					DATA.stage.stage.addChild(stageObj);
					return;
				}
				topic.subscribe((message) => {
					DATA[msgName] = message;
				});
			//否则取消订阅话题
			}else{
				//如果是站点，取消订阅话题
				if (stageName === 'waypointsStage'){
					topic.unsubscribe();
					for (var key in stageObj){
						//移除重复轨迹
						if (DATA.waypointsStage.hasOwnProperty(key)){
							var waypointsContainers = DATA.waypointsStage[key];
							for (var i = 0; i < waypointsContainers.length; i++){
								DATA.stage.stage.removeChild(waypointsContainers[i]);
							}
						}
					}
					return;
				//如果是地图，移除地图中对应的信息
				}else if (stageName === 'mapStage'){
					DATA.stage.stage.removeChild(stageObj);
					return;
				}else{
					console.log(stageObj)
					topic.unsubscribe();
					DATA.stage.stage.removeChild(stageObj);	
				}
			}
		}
	},

	/**
	 * 初始化地图信息时dispMapAndWps，订阅到地图信息调用dispMap
	 * 显示地图
	 * message:地图上现显示的所有信息
	 * 地图容器，宽高缩平移等
	 * **/
	dispMap: (message) => {
		if (DATA.mapStage){
			DATA.stage.stage.removeAllChildren();
			DATA.robotStage = null;
		}
		var innerCanvas = document.createElement('canvas');
		var innerCtx = innerCanvas.getContext('2d');
		innerCanvas.width = message.info.width;
 		innerCanvas.height = message.info.height;
		 
		if(DATA.useBase64){
			var bitmap = new createjs.Bitmap(message.data);
		}else{
			var imageData = innerCtx.createImageData(message.info.width, message.info.height);
			for ( var row = 0; row < message.info.height; row++) {
				for ( var col = 0; col < message.info.width; col++) {
					// determine the index into the map data
					var mapI = col + ((message.info.height - row - 1) * message.info.width);
					// determine the value
					var data = message.data[mapI];
					var i = (col + (row * message.info.width)) * 4;
					if (data === 100) {
						imageData.data[i] = 40;
						imageData.data[++i] = 53;
						imageData.data[++i] = 147;
						imageData.data[++i] = 255;
					} 
					else if (data === 0) 
					{
						imageData.data[i] = 232;
						imageData.data[++i] = 234;
						imageData.data[++i] = 246;
						imageData.data[++i] = 63;
					} 
					else 
					{
						imageData.data[i] = 245;
						imageData.data[++i] = 245;
						imageData.data[++i] = 245;
						imageData.data[++i] = 5; //0
					}
				}// inner for
			}// for
			innerCtx.putImageData(imageData, 0, 0);
			var bitmap = new createjs.Bitmap(innerCanvas);
		}
		
    	var rMap = message.info.width / message.info.height;
	    var width = DATA.stage.width;
	    var height = DATA.stage.height;
	    if (DATA.stage.width > DATA.stage.height){
	        width = DATA.stage.height * rMap;
	        height = DATA.stage.height;
	    }else{
	        width = DATA.stage.width;
	        height = DATA.stage.width / rMap;
	    }
	    var scale = {
    		x: width / DATA.stage.width || 1.0,
    		y: height / DATA.stage.height || 1.0
    	}

		DATA.stage.x = scale.x;
		DATA.stage.y = scale.y;
		bitmap.scaleX = DATA.stage.width / message.info.width * scale.x;
		bitmap.scaleY = DATA.stage.height / message.info.height * scale.y;
		bitmap.regX = (width - DATA.stage.width) / 2 || 0;
		bitmap.regY = (height - DATA.stage.height) / 2 || 0;
		DATA.mapScaleStage = {
			x: bitmap.scaleX,
			y: bitmap.scaleY,
			regX: bitmap.regX,
			regY: bitmap.regY
		};
		console.log(bitmap)
		DATA.mapStage = bitmap;
		
		//获取到地图数据之后再执行一次机器人姿态
		NAV.dispRobot();
		DATA.stage.stage.addChild(DATA.mapStage);
		if (DATA.loading){
			DATA.loading = false;
		}
	},

	/**
	 * 订阅到站点信息之后
	 * message为站点信息，绘制站点
	 * 给站点添加点击事件，导航到站点
	 * **/
	dispWaypoints: (message) => {
		//stage中删除重复的导航点
		if (DATA.waypointsStage){
			for (var key in DATA.waypointsStage){
				if (DATA.waypointsStage.hasOwnProperty(key)){
					var waypointsContainers = DATA.waypointsStage[key];
					for (var i = 0; i < waypointsContainers.length; i++){
						DATA.stage.stage.removeChild(waypointsContainers[i]);
					}
				}
			}
		}

		//在建图模式下不显示
		if (DATA.rosMode === NAV.RosMode.Gmapping 
			|| DATA.rosMode === NAV.RosMode.Converting)
		{
			return;
		}

		var waypointContainers = {
			goal: [],
		};

		//站点列表存放在store中显示
		store.commit('stationList',message.waypoints);
		
		for (var i = 0; i < message.waypoints.length; i++){
			var waypoint = message.waypoints[i];
			var wpInfo = JSON.parse(waypoint.header.frame_id);
			var waypointType = wpInfo.type;
			//显示在地图中
			var wpXY = TF.rosToPx(waypoint.pose.position);
			//如果不是目标站点，直接跳过
			if (waypointType !== 'goal'){
				continue;
			}
			var wpGraphics = new createjs.Graphics();
			var wpContainer = ICON[waypointType]({});
			wpContainer.x = wpXY.x;
			wpContainer.y = wpXY.y;
			//画布旋转
			wpContainer.rotation = TF.quaternionToTheta(waypoint.pose.orientation);
			wpContainer.name = waypoint.name; // bind name
			DATA.stage.stage.addChild(wpContainer);
			waypointContainers[waypointType].push(wpContainer);
			console.log(wpContainer)
			// TODO: handle wp click
			//点击站点导航到站点
			wpContainer.on('click', UI.wpClickHandle); 
		}
		console.log(createjs)
		//存放站点容器
		DATA.waypointsStage = waypointContainers;
	},

	/**
	 * 显示轨迹列表
	 * 轨迹列表存放在store中显示
	 * **/
	dispTrajectories: (message) => {
		store.commit('trajectoryList',message.trajectories);
	},

	

	/**
	 * 绘制机器人在地图上的姿态和位置
	 * position：坐标
	 * orientation:四元数转换
	 * **/
	dispRobot: (message) => {
		console.log(message)
		var pos = TF.rosToPx({
				x: message.pose.pose.position.x,
				y: message.pose.pose.position.y
		});
		if (!pos){
			return;
		}
		console.log(pos)
		//角度
		var ori = TF.quaternionToTheta(message.pose.pose.orientation);
		if (!DATA.robotPoseStage){
			DATA.robotPoseStage = ICON.robot({});
			DATA.stage.stage.addChild(DATA.robotPoseStage);
		}else{
			// if (DATA.stage.stage.contains(DATA.robotPoseStage)){
				DATA.stage.stage.addChild(DATA.robotPoseStage);
			// }
		}
		DATA.robotPoseStage.x = pos.x;
		DATA.robotPoseStage.y = pos.y;
		DATA.robotPoseStage.rotation = ori;
	},


	/**
	 * 显示隐藏全局路径
	 * icon.globalPlan:全局路径图标
	 * **/
	dispGlobalPlan: (message) => {
		if (DATA.globalPlanStage){
			DATA.stage.stage.removeChild(DATA.globalPlanStage);
		}
		DATA.globalPlanStage = ICON.globalPlan(message, {});
		DATA.stage.stage.addChild(DATA.globalPlanStage);
	},


	/**
	 * 显示隐藏局部路径
	 *ICON.localPlan：局部路径图标
	 * **/
	dispLocalPlan: (message) => {
		if (DATA.localPlanStage){
			DATA.stage.stage.removeChild(DATA.localPlanStage);
		}
		var msgMap = TF.localPlanOdomToMap(message);
		DATA.localPlanStage = ICON.localPlan(msgMap, {
			strokeColor: '#e91e63'
		});
		DATA.stage.stage.addChild(DATA.localPlanStage);
	},


	/**
	 * 显示轮廓
	 * ICON.footprint：轮廓图标
	 * **/
	dispFootprint: (message) => {
		if (DATA.footprintStage){
			DATA.stage.stage.removeChild(DATA.footprintStage);
		}
		DATA.footprintStage = ICON.footprint(message, {
			strokeColor: '#8bc34a'
		});
		DATA.stage.stage.addChild(DATA.footprintStage);
	},

	/**
	 * 显示激光
	 * ICON.laserScan：激光图标
	 * **/
	dispLaserScan: (message) => {
		if (DATA.laserScanStage){
			DATA.stage.stage.removeChild(DATA.laserScanStage);
		}
		var laserScanPoints = TF.laserScanBase_laserToMap(message);
		DATA.laserScanStage = ICON.laserScan(laserScanPoints, {
			fillColor: '#ff9800'
		});
		DATA.stage.stage.addChild(DATA.laserScanStage);
	},



	//当前地图状态，是新建还是导航中
	rosModeHandle: (mode) => {
		//如果是新建地图，改变文字
		if (mode === NAV.RosMode.Gmapping){
			console.log('新建地图》保存地图');
			store.commit('switchEditMapBtns',true);
		}else if (mode === NAV.CmdEnum.SaveMap){//如果是保存修改地图
			console.log('修改地图》保存修改')
        	if (DATA.loading){
        		DATA.loading = false;
        	}
		}else if (mode === NAV.RosMode.Converting){//如果是切换地图
			console.log('切换地图》显示地图')
		}else if (mode === NAV.RosMode.Navigation){
			if (!DATA.mapList){
				return;
			}
			UI.updateMapList(DATA.mapList);
			if (!DATA.loading){
				DATA.loading = false;
			}
		}else{

		}
	},



	zoomOut: () => {
		DATA.mapStage.regX = 0;
		DATA.mapStage.regY = 0;
		DATA.mapStage.scaleX = DATA.mapScaleStage.x;
		DATA.mapStage.scaleY = DATA.mapScaleStage.y;
	},
	

	//位置估计
	poseEstimate: () => {
		DATA.stage.stage.addEventListener('click', PAINT.pose);	
	},

	//显示菊花
	loading: (info) => {
		if (info){
			var hint = info;
			if ((typeof info) === 'object'){
				if (info.hasOwnProperty('key')){
					hint = info.info;
				}
			}
			Loading.service({text:hint});
			return;
		}else{
			let loadingInstance = Loading.service()
			loadingInstance.close();
		}
	},
};

export { 
	UI
} 